// 设备配置
import $store from '@/store/index'
import BLEconnect from './ble-connect'
import TimerDelay from '../timer-delay'
import setBufferData from './config-buffer'

let Connect = null // 蓝牙对象
let writeId = '' // 写入Id
let buffer = null // 写入数据

function write() {
    let currentsend = buffer.LeftLen > 20 ? 20 : buffer.LeftLen
    let sendnowbuf = new Uint8Array(currentsend)
    console.log('currentsend:', currentsend)
    let bufferSubarray = buffer.L2Data.subarray(buffer.HadSentLen, buffer.HadSentLen + currentsend)
    sendnowbuf.set(bufferSubarray, 0)
    console.log('sendnowbuf:', sendnowbuf)
    console.log('sendnowbuf:', sendnowbuf)
    console.log('发送长度', currentsend)
    console.log('剩余长度', buffer.LeftLen)
    const value = sendnowbuf.buffer
    console.log('writeId', writeId)
    setTimeout(() => {
        Connect.writeValue(value, writeId).then(res => {
            buffer.HadSentLen += currentsend
            buffer.LeftLen -= currentsend
            if(buffer.LeftLen > 0) {
                write()
            } else {
                console.log('配置成功')
                uni.showToast({
                    icon: 'none',
                    title: '配置成功'
                })
            }
        }).catch(err => {
            console.log('蓝牙写入失败', err)
        })
    }, 1200)
}

export default function(form) {
    buffer = setBufferData(form)
    Connect = new BLEconnect(form.deviceId)
    Connect.getCharacteristicValue().then(res => {
        Connect.getWriteValue().then(wid => {
            writeId = wid
            const value = buffer.L1Head.buffer
            setTimeout(() => {
                Connect.writeValue(value, wid).then(res => {
                    buffer.totalLen = buffer.L2Len
                    buffer.LeftLen = buffer.L2Len
                    buffer.HadSentLen = 0
                    write()
                })
            }, 1200)
        })
    })
}